package com.silence.gankio.service

import android.app.Service
import android.content.Intent
import android.media.MediaPlayer
import android.net.Uri
import android.os.Binder
import android.os.IBinder
import com.silence.gankio.R
import com.xuexiang.rxutil2.logs.RxLog

class MusicService : Service() {

    val player by lazy { MediaPlayer() }
    private val music by lazy { Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.music) }
    private val TAG = MusicService::class.java.simpleName

    override fun onBind(intent: Intent): IBinder = MusicBinder()

    override fun onCreate() {
        super.onCreate()
        RxLog.eTag(TAG, "onCreate")
        try {
            player.setDataSource(this, music)
            player.prepare()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        RxLog.eTag(TAG, "准备播放音乐")

    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        RxLog.eTag(TAG, "onStartCommand")
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onStart(intent: Intent?, startId: Int) {
        RxLog.eTag(TAG, "onStart")
        super.onStart(intent, startId)
    }

    override fun onUnbind(intent: Intent?): Boolean {
        RxLog.eTag(TAG, "onUnbind")
        return super.onUnbind(intent)
    }

    override fun onDestroy() {
        RxLog.eTag(TAG, "onDestroy")
        super.onDestroy()
    }

    inner class MusicBinder() : Binder() {

        private val TAG = MusicBinder::class.java.simpleName

        //判断是否处于播放状态
        fun isPlaying(): Boolean = player.isPlaying

        //播放或暂停歌曲
        fun play() {
            if (isPlaying()) {
                player.pause()
            } else {
                player.start()
            }
            RxLog.eTag(TAG, "播放音乐")
        }

        fun stop() {
            player.stop()
            player.release()
        }

        //返回歌曲的长度，单位为毫秒
        fun getDuration(): Int = player.duration

        //返回歌曲目前的进度，单位为毫秒
        fun getCurrenPostion(): Int = player.currentPosition

        //设置歌曲播放的进度，单位为毫秒
        fun seekTo(mesc: Int) {
            player.seekTo(mesc)
        }
    }
}
